<template>
  <div>
    <h2>员工管理</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/AdminMain/AdminHome">主页</el-breadcrumb-item>
      <el-breadcrumb-item>员工管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <i class="el-icon-s-order" style="margin-right: 5px;"></i>员工信息表
        </div>
      </template>

      <el-table
          :data="tableData"
          style="width: 100%;"
          v-loading="loading"
      >
        <el-table-column prop="employeeAccount" label="工号" />
        <el-table-column prop="employeeName" label="姓名" />
        <el-table-column prop="employeeGender" label="性别" />
        <el-table-column prop="employeeAge" label="年龄" />
        <el-table-column prop="entryTime" label="入职时间" :formatter="formatDate" />
        <el-table-column prop="staff" label="职务" />
        <el-table-column prop="employeeMessage" label="备注信息" />
        <el-table-column label="操作" align="left" width="160" header-align="left">
          <template #default="scope">
            <div style="padding-left: 0px;">
              <el-button type="primary" size="small" @click="onEdit(scope.row)" style="margin-right:5px;">编辑</el-button>
              <el-button type="danger" size="small" @click="onDelete(scope.row)">解雇</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          style="margin-top: 20px; text-align: center"
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
      >
        <template #total>
          共 {{ total }} 人
        </template>
        <template #jumper>
          跳转到
          <el-input
              class="el-pagination__editor is-in-pagination"
              v-model.number="jumperPage"
              type="number"
              size="small"
              @keyup.enter.native="jumpToPage"
              :min="1"
              :max="Math.ceil(total / pageSize)"
          />
          页
        </template>
      </el-pagination>

      <div style="text-align:center;margin-top:20px;">
        <el-button type="success" @click="onAdd">添加员工信息</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

const router = useRouter()

const tableData = ref([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const jumperPage = ref(null)

// 获取员工分页数据
const fetchData = () => {
  loading.value = true
  axios.get('/server/employee/search', {
    params: {
      page: currentPage.value,
      size: pageSize.value
    }
  })
      .then(response => {
        if (response.data.code === 200) {
          tableData.value = response.data.data.records
          total.value = response.data.data.total
        } else {
          ElMessage.error('获取数据失败: ' + response.data.message)
        }
      })
      .catch(error => {
        console.error('获取员工数据失败:', error)
        ElMessage.error('加载员工数据失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 切换页码时
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchData()
}

// 自定义跳页
const jumpToPage = () => {
  if (
      jumperPage.value >= 1 &&
      jumperPage.value <= Math.ceil(total.value / pageSize.value)
  ) {
    currentPage.value = jumperPage.value
    fetchData()
  } else {
    ElMessage.warning('请输入有效页码')
  }
}

// 首次加载
onMounted(() => {
  fetchData()
})

const onEdit = (row) => {
  router.push({
    path: '/AdminMain/EditEmployee',
    query: { employeeAccount: row.employeeAccount }
  })
}

const onDelete = (row) => {
  ElMessageBox.confirm(
      '确定要解雇工号为 ' + row.employeeAccount + ' 的员工吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 向后端发送删除请求
    axios.delete('/server/employee/delete', {
      params: { employeeAccount: row.employeeAccount }
    })
        .then(response => {
          if (response.data.code === 200) {
            ElMessage.success('已解雇该员工')
            // 从当前表格中移除该项
            tableData.value = tableData.value.filter(item => item.employeeAccount !== row.employeeAccount)
            // 或者调用 fetchData() 重新获取分页数据
          } else {
            ElMessage.error('解雇失败：' + response.data.message)
          }
        })
        .catch(error => {
          console.error('删除失败:', error)
          ElMessage.error('请求失败，请稍后重试')
        })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}


const onAdd = () => {
  router.push({
    path: '/AdminMain/AddEmployee'
  })
}

// 时间格式处理
const formatDate = (row, column, cellValue) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD') : ''
}
</script>

<style scoped>
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}
</style>
